package com.cgwx.service.impl;

import com.cgwx.config.BusinessException;
import com.cgwx.entity.Authority;
import com.cgwx.entity.Folder;
import com.cgwx.entity.Room;
import com.cgwx.mapper.AuthorityMapper;
import com.cgwx.mapper.FolderMapper;
import com.cgwx.mapper.RoomMapper;
import com.cgwx.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class RoomServiceImpl implements IRoomService {

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IFolderService folderService;

    @Resource
    private IUserRoomService userRoomService;

    @Resource
    private FolderMapper folderMapper;

    @Resource
    private AuthorityMapper authorityMapper;

    @Value("${companyRoom}")
    private String companyRoom;

    @Override
    public String getCompanyRoomId() {
        return this.companyRoom;
    }

    @Override
    public List<Room> getRoom(Room room) {
        return roomMapper.getRoom(room);
    }

    @Override
    public String getPersonalRoom(String account) {
        Room room = new Room();
        room.setRoomId(account);
        room.setRoomType("staff");
        List<Room> rooms = roomMapper.getRoom(room);
        if(rooms.isEmpty()) return null;
        else return rooms.get(0).getId();
    }

    @Override
    public String getDeptRoom(String account) {
        Room room = new Room();
        room.setRoomId(userService.getDeptIdByAccount(account));
        room.setRoomType("dept");
        List<Room> rooms = roomMapper.getRoom(room);
        if(rooms.isEmpty()) return null;
        else return rooms.get(0).getId();
    }

    @Override
    public Room getRoom(String account, String deptId, String type) {
        Room room = new Room();
        room.setRoomType(type);
        if(type.equals("staff") || type.equals("me") || type.equals("Me")) {
            room.setRoomType("staff");
            room.setRoomId(account);
        }
        else if(type.equals("dept")) room.setRoomId(deptId);
        else room.setRoomId("0");
        List<Room> rooms = roomMapper.getRoom(room);
        if(rooms.isEmpty()) return null;
        else return rooms.get(0);
    }

    @Override
    public String updateRoomById(Room room) {
        room.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        boolean result = roomMapper.updateRoomById(room);
        if(result) return "更新成功!";
        else return "更新失败!";
    }

    @Override
    public String updateAuthRoomById(Room room) {
        room.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        boolean result = roomMapper.updateAuthRoomById(room);
        if(result) return "更新成功!";
        else return "更新失败!";
    }

    @Override
    public String insertStaffRoom(Room room) {
        room.setUsedSpace(0);
        room.setRoomType("staff");
        room.setId("staff_" + generateId());
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        room.setCreateTime(now);
        room.setUpdateTime(now);
        boolean result = roomMapper.insertRoom(room);
        if(result) return "新增成功!";
        else return "新增失败!";
    }

    @Override
    public String insertDeptRoom(Room room) {
        room.setUsedSpace(0);
        room.setRoomType("dept");
        room.setId("dept_" + generateId());
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        room.setCreateTime(now);
        room.setUpdateTime(now);
        boolean result = roomMapper.insertRoom(room);
        if(result) return "新增成功!";
        else return "新增失败!";
    }

    @Override
    public boolean deleteFreeRoom(String entityRoom) {
        return roomMapper.deleteRoomById(entityRoom);
    }

    @Transactional
    @Override
    public String insertFreeRoom(String account, String name, String roomName, List<String> accountList) {
        Room room = new Room();
        String roomId = "free_" + generateId();
        room.setId(roomId);
        room.setUsedSpace(0);
        room.setRoomType("free");
        room.setRoomName(roomName);
        room.setRoomId(account);
        room.setFreeAuth("2");
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        room.setCreateTime(now);
        room.setUpdateTime(now);
        boolean result = roomMapper.insertRoom(room);
        if(!result) {
            log.error("insertFreeRoom: 空间创建失败!(1)");
            throw new BusinessException("空间创建失败!");
        }
        //文件夹根
        Folder folder = new Folder();
        folder.setParentId("root");
        folder.setCreateTime(now);
        folder.setType("folder");
        folder.setOwnerAccount(account);
        folder.setOwnerName(name);
        folder.setEntityRoom(roomId);
        folder.setEntityName(roomName);
        String entityId = folderService.generateEntityId();
        folder.setEntityId(entityId);
        result = folderMapper.insertFolder(folder);
        if(!result) {
            log.error("insertFreeRoom: 空间创建失败!(2)");
            throw new BusinessException("空间创建失败!");
        }
        //权限
        if(!userRoomService.insertUserRoom(account, entityId, roomId, now).equals("员工空间表新增成功!")){
            log.error("insertUserRoom: 员工空间表新增失败!(3)");
            throw new BusinessException("员工空间表新增失败!");
        }
        now = Timestamp.valueOf(LocalDateTime.now());
        for(String personAccount: accountList){
            if(personAccount.equals(account)) continue;
            if(!userRoomService.insertUserRoom(personAccount, entityId, roomId, now).equals("员工空间表新增成功!")){
                log.error("insertUserRoom: 员工空间表新增失败!(4)");
                throw new BusinessException("员工空间表新增失败!");
            }
        }
        Authority authority = new Authority();
        authority.setEntityId(entityId);
        authority.setPermissionType("staff");
        authority.setPermissionId(account);
        authority.setAuthorityLevel("4");
        authority.setUpdateTime(now);
        if(!authorityMapper.updateAuthority(authority)){
            log.error("insertFreeRoom: 空间创建失败!(5)");
            throw new BusinessException("权限设置失败!");
        }
        return "空间创建成功!";
    }

    @Override
    public String getUsedSpace(String account, String type) {
        Room room = new Room();
        String roomId;
        if(type == null || type.equals("staff") || type.equals("me") || type.equals("Me")) {
            roomId = account;
            room.setRoomType("staff");
        }
        else{
            roomId = userService.getDeptIdByAccount(account);
            room.setRoomType("dept");
        }
        room.setRoomId(roomId);
        room = roomMapper.getRoom(room).get(0);
        List<Room> rooms = getRoom(room);
        if(!rooms.isEmpty()) return String.valueOf(rooms.get(0).getUsedSpace());
        else return "没有该空间!";
    }

    @Override
    public String generateId() {
        return UUID.randomUUID().toString();
    }
}
